package com.jsbb.controller;

import com.jsbb.common.Message;
import com.jsbb.config.ParamsConfig;
import com.jsbb.service.sys.SysFileService;
import com.jsbb.vo.sys.SysFileVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件Controller
 *
 * @author w
 */
@RestController
@RequestMapping("/common/file")
@Tag(name = "公共模块-文件")
public class FileController {

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private ParamsConfig paramsConfig;

    @PostMapping("/upload")
    @Operation(summary = "上传")
    @Parameters({
            @Parameter(name = "module", description = "模块"),
            @Parameter(name = "file", description = "文件")
    })
    public Message<SysFileVo> upload(String module, MultipartFile file) throws Exception {
        SysFileVo sysFileVo = sysFileService.upload(file, module);
        return Message.success(sysFileVo);
    }

    @GetMapping("/download")
    @Operation(summary = "下载")
    @Parameter(name = "id", description = "ID")
    public ResponseEntity<InputStreamResource> download(String id) throws Exception {
        SysFileVo sysFileVo = sysFileService.get(id);
        String filePath;
        if (id.contains(".")) {
            filePath = paramsConfig.getFilePath() + id;
        } else {
            filePath = sysFileVo.getUrl();
        }
        FileSystemResource file = new FileSystemResource(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", id);
        return ResponseEntity.ok().headers(headers).body(new InputStreamResource(file.getInputStream()));
    }
}
